<template>
  <div class="crud-container">
    <el-button type="primary" @click="dialogVisible = true">新增</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="editRow(row)">编辑</el-button>
          <el-button type="text" @click="deleteRow(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="{{ isEdit ? '编辑' : '新增' }}">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="formData.age" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const tableData = ref([
  { id: 1, name: '张三', age: 20 },
  { id: 2, name: '李四', age: 25 }
])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formData = ref({ id: null, name: '', age: '' })

const editRow = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

const deleteRow = (row) => {
  tableData.value = tableData.value.filter(item => item.id !== row.id)
}
// 111121
const submitForm = () => {
  if (isEdit.value) {
    const index = tableData.value.findIndex(item => item.id === formData.value.id)
    if (index !== -1) {
      tableData.value[index] = { ...formData.value }
    }
  } else {
    formData.value.id = Date.now()
    tableData.value.push({ ...formData.value })
  }
  dialogVisible.value = false
  formData.value = { id: null, name: '', age: '' }
  isEdit.value = false
}
</script>

<style lang="scss" scoped>
.crud-container {
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>